package org.xin.security.component;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.xin.common.constant.Constants;
import org.xin.common.util.ClientUtil;
import org.xin.common.util.XinUtil;
import org.xin.common.util.ip.AddressUtil;
import org.xin.common.util.ip.IPUtil;
import org.xin.common.config.RedisCache;
import org.xin.security.pojo.bo.SecurityUser;
import org.xin.security.config.properties.SecurityConfigProperties;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> token验证处理 </p>
 * @modified By：$
 * @version: $
 */
@Component
public class TokenComponent {
    @Autowired
    private SecurityConfigProperties securityConfigProperties;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;
    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public SecurityUser getSecurityUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (XinUtil.noNull(token)) {
            System.out.println("===========================" + token);
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                SecurityUser user = redisCache.getCacheObject(userKey);
                return user;
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setSecurityUser(SecurityUser securityUser) {
        if (XinUtil.noNull(securityUser) && XinUtil.noNull(securityUser.getToken())) {
            refreshToken(securityUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delSecurityUser(String token) {
        if (XinUtil.noNull(token)) {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param securityUser 用户信息
     * @return 令牌
     */
    public Dict createToken(SecurityUser securityUser) {
        String token = IdUtil.fastUUID();
        securityUser.setToken(token);
        setUserAgent(securityUser);
        refreshToken(securityUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return Dict.create().set(securityConfigProperties.getToken().getHeader(), createToken(claims));
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param securityUser
     * @return 令牌
     */
    public void verifyToken(SecurityUser securityUser) {
        long expireTime = securityUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(securityUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param securityUser 登录信息
     */
    public void refreshToken(SecurityUser securityUser) {
        securityUser.setLoginTime(System.currentTimeMillis());
        securityUser.setExpireTime(securityUser.getLoginTime() + securityConfigProperties.getToken().getExpireTime() * MILLIS_MINUTE);
        // 根据uuid将securityUser缓存
        String userKey = getTokenKey(securityUser.getToken());
        redisCache.setCacheObject(userKey, securityUser, securityConfigProperties.getToken().getExpireTime(), TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param securityUser 登录信息
     */
    public void setUserAgent(SecurityUser securityUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ClientUtil.getRequest().getHeader("User-Agent"));
        String ip = IPUtil.getIpAddr(ClientUtil.getRequest());
        securityUser.setIpaddr(ip);
        securityUser.setLoginLocation(AddressUtil.getRealAddressByIP(ip));
        securityUser.setBrowser(userAgent.getBrowser().getName());
        securityUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, securityConfigProperties.getToken().getSecret()).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(securityConfigProperties.getToken().getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(securityConfigProperties.getToken().getHeader());
        if (XinUtil.noNull(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
